package com.hui.forecastapp;

import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hui.forecastapp.base.BaseFragment;
import com.hui.forecastapp.bean.WeatherBean;
import com.hui.forecastapp.db.DBManager;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import static android.content.Context.MODE_PRIVATE;

/**
 * A simple {@link Fragment} subclass.
 */
public class CityWeatherFragment extends BaseFragment implements View.OnClickListener {

    TextView tempTv, cityTv, conditionTv, windTv, HumidityTv, dateTv;
    TextView clothIndexTv, carIndexTv, coldIndexTv, sportIndexTv, raysIndexTv;
    LinearLayout futureLayout;
    ScrollView outLayout;

    String url1 = "https://wis.qq.com/weather/common?source=pc&weather_type=observe|index|rise|alarm|air|tips|forecast_24h&province=";
    String url2 = "&city=";
    String province, city;

    private WeatherBean.DataDTO.IndexDTO index;

    private SharedPreferences pref;
    private int bgNum;

    // 换壁纸的函数
    public void exchangeBg() {
        pref = getActivity().getSharedPreferences("bg_pref", MODE_PRIVATE);
        bgNum = pref.getInt("bg", 2);
        switch (bgNum) {
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_city_weather, container, false);
        initView(view);
        exchangeBg();
        // 通过activity传值获取当前fragment加载的是哪个地方的天气情况
        Bundle bundle = getArguments();
        province = bundle.getString("province");
        city = bundle.getString("city");
        // 拼凑网址
        String url = url1 + province + "&" + url2 + city;
        // 调取父类的方法访问网址
        loadData(url);
        return view;
    }

    @Override
    public void onSuccess(String result) {
        // 解析并展示数据
        try {
            parseShowData(result);
            // 调用数据库函数更新数据
            int i = DBManager.updateInfoByCity(city, result);
            if (i <= 0) {
                // 更新数据库失败，说明没有这个城市，增加这个城市记录
                DBManager.addCityInfo(province, city, result);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onError(Throwable ex, boolean isOnCallback) {
        // 数据库当中查找上一次信息显示在Fragment当中
        String content = DBManager.queryInfoByCity(city);
        if (!TextUtils.isEmpty(content)) {
            try {
                parseShowData(content);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    private void parseShowData(String result) throws ParseException {
        // 使用Gson解析数据
        WeatherBean weatherBean = new Gson().fromJson(result, WeatherBean.class);
        WeatherBean.DataDTO resultsBean = weatherBean.getData();
        // 获取指数信息集合列表
        index = resultsBean.getIndex();

        // 获取今日天气情况
        WeatherBean.DataDTO.ObserveDTO todayBean = resultsBean.getObserve();
        // 设置TextView
        cityTv.setText(city);
        String time = changeTime(todayBean.getUpdate_time());
        dateTv.setText(time);
        tempTv.setText(todayBean.getDegree() + "℃");
        windTv.setText("风力 " + todayBean.getWind_power());
        HumidityTv.setText("湿度 " + todayBean.getHumidity() + "%");
        conditionTv.setText(todayBean.getWeather());

        // 未来三天的天气
        WeatherBean.DataDTO.Forecast24hDTO futureList = resultsBean.getForecast_24h();
        // 第一天
        View itemView = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        futureLayout.addView(itemView);
        TextView idateTv = itemView.findViewById(R.id.item_center_tv_date);
        TextView iconTv = itemView.findViewById(R.id.item_center_tv_con);
        TextView itemprangeTv = itemView.findViewById(R.id.item_center_tv_temp);

        idateTv.setText(futureList.get_$2().getTime()+" 明天");
        iconTv.setText(futureList.get_$2().getDay_weather());
        itemprangeTv.setText(futureList.get_$2().getMin_degree()+"~"+futureList.get_$2().getMax_degree()+"°C");

        // 第二天
        View itemView2 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        futureLayout.addView(itemView2);
        TextView idateTv2 = itemView2.findViewById(R.id.item_center_tv_date);
        TextView iconTv2 = itemView2.findViewById(R.id.item_center_tv_con);
        TextView itemprangeTv2 = itemView2.findViewById(R.id.item_center_tv_temp);

        idateTv2.setText(futureList.get_$4().getTime()+" 后天");
        iconTv2.setText(futureList.get_$4().getDay_weather());
        itemprangeTv2.setText(futureList.get_$4().getMin_degree()+"~"+futureList.get_$4().getMax_degree()+"°C");

        // 第三天
        View itemView3 = LayoutInflater.from(getActivity()).inflate(R.layout.item_main_center, null);
        itemView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        futureLayout.addView(itemView3);
        TextView idateTv3 = itemView3.findViewById(R.id.item_center_tv_date);
        TextView iconTv3 = itemView3.findViewById(R.id.item_center_tv_con);
        TextView itemprangeTv3 = itemView3.findViewById(R.id.item_center_tv_temp);

        idateTv3.setText(futureList.get_$3().getTime()+" 大后天");
        iconTv3.setText(futureList.get_$3().getDay_weather());
        itemprangeTv3.setText(futureList.get_$3().getMin_degree()+"~"+futureList.get_$3().getMax_degree()+"°C");
    }

    private String changeTime(String update_time) throws ParseException {
        SimpleDateFormat sf1 = new SimpleDateFormat("yyyyMMddHHmm");
        SimpleDateFormat sf2 =new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String sfstr = "";
        sfstr = sf2.format(sf1.parse(update_time));
        return sfstr;
    }

    private void initView(View view) {
        tempTv = view.findViewById(R.id.frag_tv_currenttemp);
        cityTv = view.findViewById(R.id.frag_tv_city);
        conditionTv = view.findViewById(R.id.frag_tv_condition);
        windTv = view.findViewById(R.id.frag_tv_wind);
        HumidityTv = view.findViewById(R.id.frag_tv_humidity);
        dateTv = view.findViewById(R.id.frag_tv_date);

        clothIndexTv = view.findViewById(R.id.frag_index_tv_dress);
        carIndexTv = view.findViewById(R.id.frag_index_tv_washcar);
        coldIndexTv = view.findViewById(R.id.frag_index_tv_cold);
        sportIndexTv = view.findViewById(R.id.frag_index_tv_sport);
        raysIndexTv = view.findViewById(R.id.frag_index_tv_rays);

        futureLayout = view.findViewById(R.id.frag_center_layout);
        outLayout = view.findViewById(R.id.frag_outlayout);

        // 监听点击事件
        clothIndexTv.setOnClickListener(this);
        carIndexTv.setOnClickListener(this);
        coldIndexTv.setOnClickListener(this);
        sportIndexTv.setOnClickListener(this);
        raysIndexTv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder = new AlertDialog.Builder((getActivity()));
        String msg = "";
        switch (v.getId()) {
            case R.id.frag_index_tv_dress:
                builder.setTitle("穿衣指数");
                WeatherBean.DataDTO.IndexDTO.ClothesDTO cloth = index.getClothes();
                msg = cloth.getInfo() + "\n" + cloth.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_washcar:
                builder.setTitle("洗车指数");
                WeatherBean.DataDTO.IndexDTO.CarwashDTO carwash = index.getCarwash();
                msg = carwash.getInfo() + "\n" + carwash.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_cold:
                builder.setTitle("寒冷指数");
                WeatherBean.DataDTO.IndexDTO.ColdDTO cold = index.getCold();
                msg = cold.getInfo() + "\n" + cold.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_sport:
                builder.setTitle("运动指数");
                WeatherBean.DataDTO.IndexDTO.SportsDTO sport = index.getSports();
                msg = sport.getInfo() + "\n" + sport.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
            case R.id.frag_index_tv_rays:
                builder.setTitle("紫外线指数");
                WeatherBean.DataDTO.IndexDTO.SunscreenDTO rays = index.getSunscreen();
                msg = rays.getInfo() + "\n" + rays.getDetail();
                builder.setMessage(msg);
                builder.setPositiveButton("确定",null);
                break;
        }
        builder.create().show();
    }
}